package com.example.emailWeb.Socket.Proxy;

import com.example.emailWeb.ntru.encrypt.NtruProxyParameters;
import com.example.emailWeb.ntru.encrypt.NtruProxyServer;
import com.example.emailWeb.ntru.encrypt.NtruProxyUserA;
import com.example.emailWeb.ntru.polynomial.IntegerPolynomial;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class FileOwnerDemo {
    /**
     * 开启一个端口监听来自文件请求者的socket
     * 处理文件请求者发过来的data
     * @param args
     */
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(IpPort.FileOwnerPort);
        while (true){
            Socket accept = serverSocket.accept();
            //收data
            ObjectInputStream ois = null;
            PolySocketData polySocketData = receiveData(accept,ois);
            System.out.println(polySocketData);
            //发data
            deal(polySocketData,accept);
            /*NtruProxyUserA UserA = new NtruProxyUserA(NtruProxyParameters.APR2011_439);
            ProxyProcess proxyProcess = new ProxyProcess(UserA,accept);
            proxyProcess.Main(polySocketData);*/
        }
    }
    /**
     * 还需要给请求者回复data,这个socket不能关闭
     * 从输入流读取数据
     * @return
     */
    public static PolySocketData receiveData(Socket socket,ObjectInputStream ois){

        PolySocketData PSdata = null;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            PSdata = (PolySocketData) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            /*if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
        }
        return PSdata;
    }

    public static void deal(PolySocketData polySocketData,Socket socket) throws IOException {
        PrimaryKey primaryKey = new PrimaryKey(polySocketData);
        NtruProxyUserA UserA = null;
        ProxyProcess proxyProcess = null;
        if (NtruMap.fileOwnermap.containsKey(primaryKey.info)) {
            proxyProcess = NtruMap.fileOwnermap.get(primaryKey.info);
        } else {
            UserA = new NtruProxyUserA(NtruProxyParameters.APR2011_439);
            proxyProcess = new ProxyProcess(UserA,socket);
        }
        System.out.println(proxyProcess);

        proxyProcess.Main(polySocketData);
        NtruMap.fileOwnermap.put(primaryKey.info, proxyProcess);
    }
}
